/**
 * /pages/login and /pages/profession
 * VBT计算逻辑
 */

import VueEvent from "../VueEvent";
let flag_v_d_options = [-0.25, -0.18, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]
let flag_v_l_options = [0.13, 0.055, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]

let flag_v_r_options = [0.05, 0.045, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]

let flag_d_d_options = [1000, 1000, 0.25, 1000, 0.40, 1000, -0.15, 1000, 1000, 1000]
// 1小于 0大于
let flag_v2_d_way_options = [0, 0, 0, 0, 0, 0, 1, 0, 0, 0]

let flag_v2_d_options = [1000, 0.10, 0.25, 0.32, 0.35, 0.20, -0.23, 0.20, 0.25, 0.25]

let flag_v2_l_options = [1000, 0.06, 0.08, 0.12, 0.1, 0.11, -0.08, 0.11, 0.08, 0.08]





// 1小于 0大于
let flag_v2_l_way_options = [1, 1, 1, 1, 1, 1, 0, 1, 1, 1]

let flag_v2_r_options = [1000, 0.05, 0.05, 0.02, 0.05, 0.08, -0.05, 0.08, 0.05, 0.05]

let flag_v2_r_way_options = [1, 1, 1, 1, 1, 1, 0, 1, 1, 1]
let delete_index_r_options = [1000, 1000, 1000, 1000, 0.05, 1000, 1000, 1000, 1000, 1000]
let noise_options = [1000, 1000, 255, 1000, 255, 1000, 1000, 1000, , 1000, 1000]



// 动作计算类型
let action_class_options = [1, 3, 2, 3, 2, 3, 3, 3, 2, 2]



function accumulate_angle(acceleration_data) {
	let velocity_data = [0]; // 初始速度为0
	let delta_t = 0.02; // 采样频率为0.2s

	for (let i = 1; i < acceleration_data.length; i++) {
		// 使用欧拉积分方法计算速度
		let v;
		if (acceleration_data[i - 1] === acceleration_data[i]) {
			v = 0;
		} else {
			v = velocity_data[velocity_data.length - 1] + acceleration_data[i] * delta_t;
		}
		velocity_data.push(v);
	}
	return velocity_data;
}




function accumulate_acceleration_to_velocity_3(acceleration_data, time) {
	let velocity_data = [0]; // 初始速度为0
	let delta_t = time; // 采样频率

	for (let i = 1; i < acceleration_data.length; i++) {
		// 使用欧拉积分方法计算速度
		let v = velocity_data[velocity_data.length - 1] + acceleration_data[i] * delta_t;
		velocity_data.push(v);
	}

	return velocity_data;
}

function accumulate_acceleration_to_velocity_4(acceleration_data, time, l, r, arg) {
	let velocity_data = [0]; // 初始速度为0
	let delta_t = time; // 采样频率

	for (let i = 1; i < acceleration_data.length; i++) {
		// 使用梯形积分方法计算速度
		let v = velocity_data[velocity_data.length - 1] + ((acceleration_data[i] + acceleration_data[i - 1]) / 2) *
			delta_t;
		if (acceleration_data[i] > l && acceleration_data[i] < r) {
			// if(Math.abs(acceleration_data[i])<0.12){
			v = v * arg;
		}
		velocity_data.push(v);
	}

	return velocity_data;
}

function accumulate_acceleration_to_velocity_44(acceleration_data, time) {
	let velocity_data = [0]; // 初始速度为0
	let delta_t = time; // 采样频率

	for (let i = 1; i < acceleration_data.length; i++) {
		// 使用梯形积分方法计算速度
		let v = velocity_data[velocity_data.length - 1] + ((acceleration_data[i] + acceleration_data[i - 1]) / 2) *
			delta_t;
		velocity_data.push(v);
	}

	return velocity_data;
}

function function_progress_angle_to_y(measured_acceleration_x, measured_acceleration_y, measured_acceleration_z,
	angular_velocity_xy, angular_velocity_xz, angular_velocity_yz) {
	let acceleration_data = [];
	let angular_x = accumulate_angle(angular_velocity_yz)
	let angular_z = accumulate_angle(angular_velocity_xy)
	for (let i = 0; i < measured_acceleration_x.length; i++) {
		// 本时刻真正的竖直方向加速度
		let y =
			measured_acceleration_y[i] * Math.cos(angular_x[i]) * Math.cos(angular_z[i]) +
			measured_acceleration_z[i] * Math.sin(angular_x[i]) +
			measured_acceleration_x[i] * Math.sin(angular_z[i]);

		acceleration_data.push(parseFloat(y.toFixed(7)));

	}
	return acceleration_data
}
// 滤波器函数
function filter1(data, cutlow, cuthigh, over_high) {
	let L = cuthigh - cutlow;
	for (let i = 0; i < data.length; i++) {
		if (Math.abs(data[i]) > cuthigh && Math.abs(data[i]) < over_high) {
			data[i] = data[i];
			continue;
		} else if (Math.abs(data[i]) < cutlow) {
			data[i] = 0;
			continue;
		} else if (Math.abs(data[i]) > over_high) {
			if (data[i] > 0) {
				data[i] = over_high;
				continue;
			} else {
				data[i] = -over_high;
				continue;
			}
		} else {
			data[i] = 0.3 * data[i];
			continue;
		}
	}
	return data;
}

// 计算正数的个数
function post_num(velocities, speedThreshold) {
	let num = 0;
	for (let i of velocities) {
		if (i > speedThreshold) {
			num++;
		}
	}
	return num;
}


// 积分法求速度
function accumulateAccelerationToVelocity(acceleration_data, time) {
	let velocity_data = [0]; // 初始速度为0
	for (let i = 1; i < acceleration_data.length; i++) {
		// 使用欧拉积分方法，计算速度
		let delta_t = time; // 采样频率为0.2s
		let v;
		if (acceleration_data[i - 1] === acceleration_data[i] && Math.abs(acceleration_data[i]) <= 1) {
			// 如果加速度保持不变且加速度小于等于1
			v = 0;
		} else {
			v = velocity_data[velocity_data.length - 1] + acceleration_data[i] * delta_t;
		}
		velocity_data.push(v);
	}
	return velocity_data;
}

function longestIncreasingSubsequence(arr) {
	if (arr.length === 0) return [];

	let maxLength = 0; // 记录最长子序列长度
	let maxStartIndex = 0; // 记录最长子序列的起始索引
	let currentStart = 0; // 记录当前上升序列的起始索引

	for (let i = 1; i < arr.length; i++) {
		if (arr[i] <= arr[i - 1]) {
			// 当前元素小于等于前一个元素，意味着上升序列终止
			let length = i - currentStart;
			if (length > maxLength) {
				maxLength = length;
				maxStartIndex = currentStart;
			}
			currentStart = i; // 重新记录新序列的起点
		}
	}

	// 处理最后一段可能是最长的情况
	if (arr.length - currentStart > maxLength) {
		maxLength = arr.length - currentStart;
		maxStartIndex = currentStart;
	}

	return arr.slice(maxStartIndex, maxStartIndex + maxLength);
}

function get_lr(v_long, v_short) {
	let l = 0;
	let r = 0;

	for (let i = 0; i < v_long.length; i++) {
		if (v_long[i] == v_short[0]) {
			l = i;
			let check = true;
			for (let j = 0; j < Math.min(4, v_short.length); j++) {
				if (v_long[i + j] != v_short[j]) {
					check = false;
					break;
				}
			}
			if (check == true) {
				r = i + v_short.length - 1;
			}
		}
	}
	// console.log("l r",l,r)
	return [l, r];
}

function cal_v_up(data, arg) {
	for (let i = 0; i < data.length; i++) {
		if (data[i] < arg) {
			return data.slice(0, i)
		}
	}
	return data
}
// 速度分割函数修改前
// let [v_up, v_down, acceleration_up, , order] = cut_list(velocities, bef_velocities);
function new_cut_list(vvv, acc_data, bef_vvv, action) {
	let ll = 0;
	let rr = 0;
	[ll, rr] = get_lr(bef_vvv, vvv)
	let order = [
		[0],
		[ll, rr]
	]
	let v_down = [];
	for (let i = 0; i < ll; i++) {
		if (bef_vvv[i] < -0.05) {
			v_down.push(bef_vvv[i]);
		}
	}
	// if (action == 4) {
	// 	vvv = cal_v_up(vvv,0.02)
	// }else if (action==3){

	// 	vvv = cal_v_up(vvv,0.01)
	// }
	let acceleration_up = acc_data.slice(ll, rr);
	return [vvv, v_down, acceleration_up, order];
}

function cut_list(velocities, speedThreshold, acceleration_data, bef_velocities) {

	let upward_moves = [];
	let downward_moves = [];
	let upward_acceleration = [];
	let downward_acceleration = [];
	let order = [];
	let num = 0;
	let downn = [];
	// console.log("bef_velocities",bef_velocities);
	// console.log("velocities",velocities);
	let ll = 0;
	let rr = 0;
	[ll, rr] = get_lr(bef_velocities, velocities)
	// console.log("ll",ll)
	// console.log("rr",rr)
	// console.log("acceleration_data!!!!",acceleration_data);
	let ac_up = longestIncreasingSubsequence(acceleration_data);
	// console.log("ac_up",ac_up)
	num = post_num(velocities, speedThreshold);
	num = num < 400 ? num : 400; // 限制最大值为 400
	// i - start_index > num * ts这里的参数！！！！！！！！！有三个
	let ts = 0.01;
	// 检查输入是否为空
	if (!velocities || velocities.length === 0) {
		return [upward_moves, downward_moves]; // 返回两个空数组
	}

	let current_move = null; // null: 未开始, "up": 向上, "down": 向下
	let start_index = 0; // 当前运动段的起始索引

	for (let i = 0; i < velocities.length; i++) {
		let value = velocities[i];
		// 判断当前速度是否大于速度阈值
		if (Math.abs(value) >= speedThreshold) {
			// 确定当前运动方向
			let move_type = value > 0 ? "up" : "down";

			// 如果当前运动段还未开始，记录起始位置
			if (current_move === null) {
				current_move = move_type;
				start_index = i;
			} else if (current_move !== move_type) {
				// 如果运动方向发生改变，保存当前运动段
				if (current_move === "up" && i - start_index > num * ts) {
					upward_moves.push(velocities.slice(start_index, i));
					upward_acceleration.push(acceleration_data.slice(start_index, i));
					order.push([start_index, i]);
				} else {
					downward_moves.push(velocities.slice(start_index, i));
					downward_acceleration.push(acceleration_data.slice(start_index, i));
				}

				// 更新当前运动段
				current_move = move_type;
				start_index = i;
			}
		} else {
			// 如果当前速度低于阈值且已开始记录运动段
			if (current_move !== null) {
				// 保存当前运动段
				if (current_move === "up" && i - start_index > num * ts) {
					upward_moves.push(velocities.slice(start_index, i));
					upward_acceleration.push(acceleration_data.slice(start_index, i));
					order.push([start_index, i]);
				} else {
					downward_moves.push(velocities.slice(start_index, i));
					downward_acceleration.push(acceleration_data.slice(start_index, i));
				}
				current_move = null;
			}
		}
	}

	// 处理最后一个运动段
	if (current_move !== null) {
		if (current_move === "up" && velocities.length - start_index > num * ts) {
			upward_moves.push(velocities.slice(start_index, velocities.length));
			upward_acceleration.push(acceleration_data.slice(start_index, velocities.length));
			order.push([start_index, velocities.length]);
		} else {
			downward_moves.push(velocities.slice(start_index, velocities.length));
			downward_acceleration.push(acceleration_data.slice(start_index, velocities.length));
		}
	}
	order = [
		[0],
		[ll, rr]
	]
	// return [bef_velocities.slice(x_up_l,x_up_r), bef_velocities.slice(y_up_l,y_up_r), acceleration_data.slice(x_up_l,x_up_r), acceleration_data.slice(y_up_l,y_up_r), order];
	// return [upward_moves, downn, ac_up, downward_acceleration, order];
	return [velocities, downn, ac_up, downward_acceleration, order];
	// return [upward_moves, downward_moves, upward_acceleration, downward_acceleration, order];
}
// displace_order(displace, velocities) 
function check_flag_d(data, x) {
	let flag = false
	for (let i = 0; i < data.length; i++) {
		if (data[i] > x) {
			flag = true
			break
		}
	}
	return flag
}

function check_flag_d_ddd(data, x) {
	let flag = false
	for (let i = 0; i < data.length; i++) {
		if (data[i] < x) {
			flag = true
			break
		}
	}
	return flag
}

function check_flag_d_other(data, x, y) {
	let flag = false
	for (let i = 0; i < data.length; i++) {
		if (data[i] > x || data[i] < y) {
			flag = true
			break
		}
	}
	return flag
}

function find_index_upper(data, l, r, val, cls) {
	// 0大于  1小于
	console.log("data, l, r, val, cls", data, l, r, val, cls)
	let flag = false;
	for (let i = l; i < r; i++) {
		if (cls == 1 && data[i] < val) {
			console.log("true,i")
			return [1, i]
		} else if (cls == 0 && data[i] > val) {
			console.log("true,i")
			return [1, i]
		}
	}
	console.log("false,0")
	return [0, 0]
}






function find_index_lower(data, l, r, val, cls) {
	// 0大于  1小于
	let flag = 0;
	for (let i = l; i >= r; i--) {
		if (cls == 1 && data[i] < val) {
			return [1, i]
		} else if (cls == 0 && data[i] > val) {
			return [1, i]
		}
	}
	return [0, 0]
}

function find_index_dist(data, l, r, val, cls) {
	// 0大于  1小于
	let flag = 0;
	for (let i = l; i < r; i++) {
		if (i == 0) continue
		let distance = data[i] - data[i - 1]
		if (cls == 1 && distance < val) {
			return [1, i]
		} else if (cls == 0 && distance > val) {
			return [1, i]
		}
	}
	return [0, 0]
}

function action1(displacements, speeds, action) {
	let flag_v_d = flag_v_d_options[action];
	let flag_v_l = flag_v_l_options[action];
	let flag_v_r = flag_v_r_options[action];
	let flag_d_d = flag_d_d_options[action];
	let v_disp = [0, 0, 0, 0.15, 0, 0.15, 0, 0.15, 0, 0.15][action];
	let flag_v2_d = flag_v2_d_options[action]
	let flag_v2_d_way = flag_v2_d_way_options[action]
	let flag_v2_l = flag_v2_l_options[action]
	let flag_v2_l_way = flag_v2_l_way_options[action]
	let flag_v2_r = flag_v2_r_options[action]
	let flag_v2_r_way = flag_v2_r_way_options[action]
	console.log(
		`flag_v_d: ${flag_v_d}, ` +
		`flag_v_l: ${flag_v_l}, ` +
		`flag_v_r: ${flag_v_r}, ` +
		`flag_d_d: ${flag_d_d}, ` +
		`v_disp: ${v_disp}, ` +
		`flag_v2_d: ${flag_v2_d}, ` +
		`flag_v2_d_way: ${flag_v2_d_way}, ` +
		`flag_v2_l: ${flag_v2_l}, ` +
		`flag_v2_l_way: ${flag_v2_l_way}, ` +
		`flag_v2_r: ${flag_v2_r}, ` +
		`flag_v2_r_way: ${flag_v2_r_way}`
	);
	let dd = 0;
	let ll = 0;
	let rr = 0;

	let l_true = 0;
	let r_true = 0;


	let v_data = []
	let dd_flag = 0;
	// let dd_index = 0
	let res_flag = 0[dd_flag, dd] = find_index_upper(displacements, 0, displacements.length, flag_v_d, 1)
	// [v_data , dd_flag,dd_index,res_flag]
	console.log("YESSS")
	console.log("dd_flag_dd", dd_flag, dd)
	if (dd_flag == 0) return [
			[0], 0, 0, 0
		]
		[l_true, ll] = find_index_upper(speeds, dd, speeds.length, flag_v_l, 0)
	if (l_true == 0) return [
			[0], 0, 0, 0
		]
		[r_true, rr] = find_index_upper(speeds, ll, speeds.length, flag_v_r, 1)
	if (r_true == 0) return [
		[0], 0, 0, 0
	]
	console.log("temp_res", speeds.slice(ll, rr), dd_flag, dd, r_true)
	return [speeds.slice(ll, rr), dd_flag, dd, r_true]
}



function action2(displacements, speeds, action) {
	let flag_v_d = flag_v_d_options[action];
	let flag_v_l = flag_v_l_options[action];
	let flag_v_r = flag_v_r_options[action];
	let flag_d_d = flag_d_d_options[action];
	let v_disp = [0, 0, 0, 0.15, 0, 0.15, 0, 0.15][action];
	let flag_v2_d = flag_v2_d_options[action]
	let flag_v2_d_way = flag_v2_d_way_options[action]
	let flag_v2_l = flag_v2_l_options[action]
	let flag_v2_l_way = flag_v2_l_way_options[action]
	let flag_v2_r = flag_v2_r_options[action]
	let flag_v2_r_way = flag_v2_r_way_options[action]

	let dd = 0;
	let ll = 0;
	let rr = 0;

	let l_true = false;
	let r_true = false;


	let v_data = []
	let dd_flag = false;
	// let dd_index = 0
	let res_flag = false

	[dd_flag, dd] = find_index_upper(displacements, 0, displacements.length, flag_v2_d, flag_v2_d_way)
	// [v_data , dd_flag,dd_index,res_flag]
	if (dd_flag == false) return [
			[], false, 0, false
		]
		[l_true, ll] = find_index_lower(speeds, dd, 0, flag_v2_l, flag_v2_l_way)
	if (l_true == false) return [
			[], false, 0, false
		]
		[r_true, rr] = find_index_upper(speeds, dd, speeds.length, flag_v2_r, flag_v2_r_way)
	if (r_true == false) return [
		[], false, 0, false
	]
	return [speeds.slice(ll, rr), dd_flag, dd, r_true]



}


function action3(displacements, speeds, action) {
	let flag_v_d = flag_v_d_options[action];
	let flag_v_l = flag_v_l_options[action];
	let flag_v_r = flag_v_r_options[action];
	let flag_d_d = flag_d_d_options[action];
	let v_disp = [0, 0, 0, 0.15, 0, 0.15, 0, 0.15][action];
	let flag_v2_d = flag_v2_d_options[action]
	let flag_v2_d_way = flag_v2_d_way_options[action]
	let flag_v2_l = flag_v2_l_options[action]
	let flag_v2_l_way = flag_v2_l_way_options[action]
	let flag_v2_r = flag_v2_r_options[action]
	let flag_v2_r_way = flag_v2_r_way_options[action]

	let dd = 0;
	let ll = 0;
	let rr = 0;

	let l_true = false;
	let r_true = false;


	let v_data = []
	let dd_flag = false;
	// let dd_index = 0
	let res_flag = false

	[dd_flag, dd] = find_index_dist(displacements, 0, displacements.length, flag_v2_d, flag_v2_d_way)
	// [v_data , dd_flag,dd_index,res_flag]
	if (dd_flag == false) return [
			[], false, 0, false
		]
		[l_true, ll] = find_index_lower(speeds, dd, 0, flag_v2_l, flag_v2_l_way)
	if (l_true == false) return [
			[], false, 0, false
		]
		[r_true, rr] = find_index_upper(speeds, dd, speeds.length, flag_v2_r, flag_v2_r_way)
	if (r_true == false) return [
		[], false, 0, false
	]
	return [speeds.slice(ll, rr), dd_flag, dd, r_true]



}



function action_check(displacements, speeds, action) {
	console.log("displacement,speed,action", displacements, speeds, action)
	let action_class = action_class_options[action]
	console.log("action_class", action_class)
	let res = []
	if (action_class == 1) {
		// 0深蹲 1卧推
		res = action1(displacements, speeds, action)
	} else if (action_class == 2) {
		// 2硬拉 4高翻
		res = action2(displacements, speeds, action)
	} else if (action_class == 3) {
		// 3俯身划船  5杠铃推肩  6高位下拉  7坐姿推肩
		res = action3(displacements, speeds, action)
	}
	console.log("res", res)
	return res
}



function displace_order_new(displacements, speeds, action) {
	// 0 深蹲 1 卧推 2 硬拉 3 俯身划船 4 高翻 5 杠铃推肩 6 高位下拉 7坐姿推肩
	const defaultReturn = [
		[], 0, 0, 0
	];

	// 获取配置参数
	let flag_v_d = flag_v_d_options[action];
	let flag_v_l = flag_v_l_options[action];
	let flag_v_r = flag_v_r_options[action];
	let flag_d_d = flag_d_d_options[action];
	let v_disp = [0, 0, 0, 0.15, 0, 0.15, 0, 0.15][action];
	let flag_v2_d = flag_v2_d_options[action]
	let flag_v2_d_way = flag_v2_d_way_options[action]
	let flag_v2_l = flag_v2_l_options[action]
	let flag_v2_l_way = flag_v2_l_way_options[action]
	let flag_v2_r = flag_v2_r_options[action]
	let flag_v2_r_way = flag_v2_r_way_options[action]
	// 输入检查
	if (!Array.isArray(displacements) || !Array.isArray(speeds)) {
		console.log("输入数据格式错误");
		return defaultReturn;
	}
	if (displacements.length !== speeds.length) {
		console.log("数据不等长");
		return defaultReturn;
	}

	let velocities = [];
	let ck_flag = 0;
	let l_true = false;
	let r_true = false;
	let displacementTriggered = false;
	let ll = 0,
		rr = 0,
		dd = 0;
	// 检查flag_d条件
	let flag_d = true;

	let v_data = []
	let dd_flag = false;
	let dd_index = 0
	let res_flag = false

	let hc_start = 0;
	if (action == 2) { // 硬拉
		flag_d = check_flag_d(displacements, 0.25);
	} else if (action == 4) { // 高翻
		flag_d = check_flag_d(displacements, 0.40);
	}
	// else if (action == 6) { // 高位下拉
	// 	flag_d = check_flag_d_ddd(displacements, -0.15);
	// }

	let r_hc = 0;

	let action_class = action_class_options[action]
	// console.log("action_class", action_class)


	if (action_class == 0) { //卧推
		let flag_hc = false
		// 0大于  1小于
		displacementTriggered = true
		for (let i = 0; i < displacements.length && (!l_true || !r_true); i++) {
			if (i == 0) continue
			if (flag_hc == false) {
				if (flag_v2_d_way == 0) {
					if (displacements[i] > displacements[i - 1]) { //  高位下拉 <
						let current_diff = displacements[i] - displacements[hc_start]
						if (current_diff > flag_v2_d) { //  <-0.14
							// 高位下拉 5s等待时间
							dd = i
							// console.log("I find dd", dd)
							flag_hc = true
						}
					} else {
						hc_start = i;
					}
				} else if (flag_v2_d_way == 1) {
					if (displacements[i] < displacements[i - 1]) { //  高位下拉 <
						let current_diff = displacements[i] - displacements[hc_start]
						if (current_diff < flag_v2_d) { //  <-0.14
							// 高位下拉 5s等待时间
							dd = i
							// console.log("I find dd", dd)
							flag_hc = true
						}
					} else {
						hc_start = i;
					}
				}
			}


			// !!!!!!!!!!!!
			if (flag_hc) {
				for (let k = dd; k < speeds.length; k++) {

					if (flag_v2_l_way == 1) {
						if (speeds[k] < flag_v2_l) {
							ll = k;
							// console.log("I find ll", ll)
							l_true = true;
							// console.log("ll", ll)
							break;
						}
					} else {
						if (speeds[k] > flag_v2_l) {
							ll = k;
							// console.log("I find ll", ll)
							l_true = true;
							// console.log("ll", ll)
							break;
						}
					}

				}
				if (l_true) {
					// 向右找右边界
					for (let k = ll; k < speeds.length; k++) {
						if (flag_v2_r_way == 1) {
							if (speeds[k] < flag_v2_r) {
								rr = k;
								// console.log("I find rr", rr)
								r_true = true;
								// console.log("rr", rr)
								if (flag_d)
									res_flag = true
								break;
							}
						} else {
							if (speeds[k] > flag_v2_r) {
								rr = k;
								// console.log("I find rr", rr)
								r_true = true;
								// console.log("rr", rr)
								if (flag_d)
									res_flag = true
								break;
							}
						}
					}
				}

				// console.log("d l r", flag_hc, l_true, r_true)
				if (l_true && r_true) {
					// console.log("dd ll rr ",dd,ll,rr)
					// if(action!=3){
					// console.log("前后到满足")
					// console.log("ll rr ", ll, rr)
					for (let k = ll; k <= rr; k++) {
						velocities.push(speeds[k]);
					}
					break;
				} else {
					flag_hc = false
					l_true = false
					r_true = false
				}
			}



		}

		// console.log("ck_flag,dd,ll,rr", ck_flag, dd, ll, rr)
	} else if (action_class == 1) {
		// console.log("d,l,r",flag_v_d,flag_v_l,flag_v_r)
		for (let i = 0; i < displacements.length; i++) {
			if (!displacementTriggered && displacements[i] < flag_v_d) {
				dd = i;
				displacementTriggered = true;
			}

			if (displacementTriggered) {
				// 检查左边界
				if (!l_true) {
					if (speeds[i] > flag_v_l) {
						l_true = true;
					}
				}

				// 收集速度数据
				if (l_true) {
					if (speeds[i] > flag_v_l) {
						velocities.push(speeds[i]);
					}
				}

				// 检查右边界
				if (l_true && !r_true) {
					if (speeds[i] < flag_v_r) {
						r_true = true;
						if (flag_d)
							res_flag = true
						break;
					}
				}
			}
		}
	} else if (action_class == 2) {
		let flag_hc = false
		// 0大于  1小于
		displacementTriggered = true
		for (let i = 0; i < displacements.length && (!l_true || !r_true); i++) {
			if (i == 0) continue
			if (flag_hc == false) {
				if (flag_v2_d_way == 0) {
					if (displacements[i] > flag_v2_d) { //  高位下拉 <
						// 高位下拉 5s等待时间
						dd = i
						// console.log("I find dd", dd)
						flag_hc = true
					} else {
						hc_start = i;
					}
				} else if (flag_v2_d_way == 1) {
					if (displacements[i] < flag_v2_d) { //  高位下拉 <
						// 高位下拉 5s等待时间
						dd = i
						// console.log("I find dd", dd)
						flag_hc = true
					} else {
						hc_start = i;
					}

				}
			}


			// !!!!!!!!!!!!
			if (flag_hc) {
				for (let k = dd; k >= 0; k--) {

					if (flag_v2_l_way == 1) {
						if (speeds[k] < flag_v2_l) {
							ll = k;
							// console.log("I find ll", ll)
							l_true = true;
							// console.log("ll", ll)
							break;
						}
					} else {
						if (speeds[k] > flag_v2_l) {
							ll = k;
							// console.log("I find ll", ll)
							l_true = true;
							// console.log("ll", ll)
							break;
						}
					}

				}
				// 向右找右边界
				for (let k = dd; k < speeds.length; k++) {
					if (flag_v2_r_way == 1) {
						if (speeds[k] < flag_v2_r) {
							rr = k;
							// console.log("I find rr", rr)
							r_true = true;
							// console.log("rr", rr)
							if (flag_d)
								res_flag = true
							break;
						}
					} else {
						if (speeds[k] > flag_v2_r) {
							rr = k;
							// console.log("I find rr", rr)
							r_true = true;
							// console.log("rr", rr)
							if (flag_d)
								res_flag = true
							break;
						}
					}
				}
				// console.log("d l r", flag_hc, l_true, r_true)
				if (l_true && r_true) {
					// console.log("dd ll rr ",dd,ll,rr)
					// if(action!=3){
					// console.log("前后到满足")
					// console.log("ll rr ", ll, rr)
					for (let k = ll; k <= rr; k++) {
						velocities.push(speeds[k]);
					}
					break;
				} else {
					flag_hc = false
					l_true = false
					r_true = false
				}
			}



		}

		// console.log("ck_flag,dd,ll,rr", ck_flag, dd, ll, rr)
	} else if (action_class == 3) {
		let flag_hc = false
		// 0大于  1小于
		displacementTriggered = true
		for (let i = 0; i < displacements.length && (!l_true || !r_true); i++) {
			if (i == 0) continue
			if (flag_hc == false) {
				if (flag_v2_d_way == 0) {
					if (displacements[i] > displacements[i - 1]) { //  高位下拉 <
						let current_diff = displacements[i] - displacements[hc_start]
						if (current_diff > flag_v2_d) { //  <-0.14
							// 高位下拉 5s等待时间
							dd = i
							// console.log("I find dd", dd)
							flag_hc = true
						}
					} else {
						hc_start = i;
					}
				} else if (flag_v2_d_way == 1) {
					if (displacements[i] < displacements[i - 1]) { //  高位下拉 <
						let current_diff = displacements[i] - displacements[hc_start]
						if (current_diff < flag_v2_d) { //  <-0.14
							// 高位下拉 5s等待时间
							dd = i
							// console.log("I find dd", dd)
							flag_hc = true
						}
					} else {
						hc_start = i;
					}
				}
			}


			// !!!!!!!!!!!!
			if (flag_hc) {
				for (let k = dd; k >= 0; k--) {

					if (flag_v2_l_way == 1) {
						if (speeds[k] < flag_v2_l) {
							ll = k;
							// console.log("I find ll", ll)
							l_true = true;
							// console.log("ll", ll)
							break;
						}
					} else {
						if (speeds[k] > flag_v2_l) {
							ll = k;
							// console.log("I find ll", ll)
							l_true = true;
							// console.log("ll", ll)
							break;
						}
					}

				}
				// 向右找右边界
				for (let k = dd; k < speeds.length; k++) {
					if (flag_v2_r_way == 1) {
						if (speeds[k] < flag_v2_r) {
							rr = k;
							// console.log("I find rr", rr)
							r_true = true;
							// console.log("rr", rr)
							if (flag_d)
								res_flag = true
							break;
						}
					} else {
						if (speeds[k] > flag_v2_r) {
							rr = k;
							// console.log("I find rr", rr)
							r_true = true;
							// console.log("rr", rr)
							if (flag_d)
								res_flag = true
							break;
						}
					}
				}
				// console.log("d l r", flag_hc, l_true, r_true)
				if (l_true && r_true) {
					// console.log("dd ll rr ",dd,ll,rr)
					// if(action!=3){
					// console.log("前后到满足")
					// console.log("ll rr ", ll, rr)
					for (let k = ll; k <= rr; k++) {
						velocities.push(speeds[k]);
					}
					break;
				} else {
					flag_hc = false
					l_true = false
					r_true = false
				}
			}



		}

		// console.log("ck_flag,dd,ll,rr", ck_flag, dd, ll, rr)
	}


	if (action_class == 3 && res_flag == true) {
		if (action == 6) {
			let cnt = 0
			for (let i = ll; i <= rr; i++) {
				if (speeds[i] < 0) {
					cnt++;
					if (cnt == 10) {
						break
					}
				}
			}
			if (cnt < 10) res_flag = false
		} else {
			let cnt = 0
			for (let i = ll; i <= rr; i++) {
				if (speeds[i] > 0) {
					cnt++;
					if (cnt == 10) {
						break
					}
				}
			}
			if (cnt < 10) res_flag = false
		}
	}

	// console.log("res",velocities,displacementTriggered,ck_flag,res_flag)
	return [
		velocities.length > 0 ? velocities : [],
		displacementTriggered,
		dd,
		res_flag
	];

}








// 检测到 N 个连续接近于 0 的数据
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
function is_connect_n0(data, index, N, threshold) {
	let n = 0;
	let flag = 0;
	let flag2 = 0;
	let x = 0;

	for (let i = 0; i < data.length - index; i++) {
		let element = data[index + i];

		if (Math.abs(element) <= threshold) {
			n++;
			flag = 1;
		} else {
			flag = 0;
			n = 0;
		}

		if (n === N && flag === 1) {
			x = i;
			flag2 = 1;
			break;
		}
	}

	return [flag2, index + x];
}

function accumulate_average_v(v_cut) {
	let average_v = [];

	for (let segment of v_cut) {
		if (segment.length > 0) {
			let average_speed = segment.reduce((sum, val) => sum + val, 0) / segment.length;
			average_v.push(average_speed);
		}
	}

	return average_v;
}

function VBT_juge_group_plasticity_low(v, loss, n, s) {
	// 在函数内部定义计数变量
	let count_weight_light = 0;
	let count_weight_heavy = 0;
	let info = "目前没你鸟事,继续练你的";

	if (v < 0.5) {
		count_weight_heavy++;
		if (count_weight_heavy >= 3) {
			count_weight_heavy = 0;
			info = "菜就减杠铃重量";
		}
	} else if (v > 0.75) {
		count_weight_light++;
		if (count_weight_light >= 3) {
			count_weight_light = 0;
			info = "菜就加杠铃重量";
		}
	} else {
		if (loss <= 0.3) {
			if (n >= 12) {
				if (loss >= 0.1) {
					info = "你最好只做十二个";
				} else {
					info = "菜就加杠铃重量";
				}
			} else {
				info = "目前没你鸟事,继续练你的";
			}
		} else {
			if (n >= 8) {
				info = "你最好只做八个";
			} else {
				info = "菜就减杠铃重量";
			}
		}
	}

	return info;
}

function VBT_juge_group_plasticity_up(v, loss, n, s) {
	// 在函数内部定义计数变量
	let count_weight_light = 0;
	let count_weight_heavy = 0;
	// 初始化提示信息
	let info = "目前没你鸟事,继续练你的";

	// 根据速度 v 进行判断
	if (v < 0.4) {
		count_weight_heavy++;
		if (count_weight_heavy >= 3) {
			count_weight_heavy = 0;
			info = "菜就减杠铃重量";
		}
	} else if (v > 0.6) {
		count_weight_light++;
		if (count_weight_light >= 3) {
			count_weight_light = 0;
			info = "菜就加杠铃重量";
		}
	} else {
		// 根据损失率 loss 进行判断
		if (loss <= 0.3) {
			if (n >= 12) {
				if (loss >= 0.1) {
					info = "你最好只做十二个";
				} else {
					info = "菜就加杠铃重量";
				}
			} else {
				info = "目前没你鸟事,继续练你的";
			}
		} else {
			if (n >= 8) {
				info = "你最好只做八个";
			} else {
				info = "菜就减杠铃重量";
			}
		}
	}

	return info;
}

function velocity_loss_try(v_cut_up) {
	let loss_data = [];
	let average_speeds = accumulate_average_v(v_cut_up); // 使用 accumulateAverageV 计算平均速度
	// console.log("average_speeds~!!!!!",average_speeds);
	for (let i = 0; i < average_speeds.length; i++) {
		if (i === 0) {
			loss_data.push(0);
		} else {
			loss_data.push((Math.max(...average_speeds) - average_speeds[i]) / Math.max(...average_speeds));
		}
	}

	return [loss_data, average_speeds];
}
// 速度
function averagy_v(v_up) {
	if (v_up.length === 0) {
		return 0;
	}
	let sum = 0;
	for (let i = 0; i < v_up.length; i++) {
		sum += v_up[i];
	}
	return sum / v_up.length;
}
// 功率的计算
function caculate_power(v_up, force_data) {
	let power_data = [];
	for (let i = 0; i < Math.min(v_up.length, force_data.length); i++) {
		power_data.push(v_up[i] * force_data[i]);
	}
	return power_data;
}

function averagy_power(powerArray) {
	if (powerArray.length === 0) {
		return 0;
	}
	let sum = 0;
	for (let i = 0; i < powerArray.length; i++) {
		sum += powerArray[i];
	}
	return sum / powerArray.length;
}

function averagy_force(force_data) {
	// 检查数组是否为空，如果为空则直接返回 0，避免除以零错误
	if (force_data.length === 0) {
		return 0;
	}
	let sum = 0;
	// 使用 for 循环遍历数组，将每个元素累加到 sum 中
	for (let i = 0; i < force_data.length; i++) {
		sum += force_data[i];
	}
	// 计算平均值并返回
	return sum / force_data.length;
}
// calculate_force(acceleration_up, m_data, local_g)
function calculate_force(acceleration, mass, gravity) {
	let force_data = [];
	mass = Number(mass);
	gravity = Number(gravity);
	for (let i = 0; i < acceleration.length; i++) {
		let tp = mass * (acceleration[i] + gravity)
		force_data.push(tp)
	}
	return force_data;
}

function generateTimeList(acceleration_up) {
	let time_list = [];
	for (let i = 0; i < acceleration_up.length; i++) {
		time_list.push(0.2 * i);
	}
	return time_list;
}

function getTimeToPeakForce(time_list, force_data) {
	let maxIndex = 0;
	let maxForce = force_data[0];
	// 遍历 force_data 数组，找出最大值及其索引
	for (let i = 1; i < force_data.length; i++) {
		if (force_data[i] > maxForce) {
			maxForce = force_data[i];
			maxIndex = i;
		}
	}
	// 使用最大值的索引从 time_list 中获取对应的值
	return time_list[maxIndex];
}

function peak_force(force_data) {
	if (force_data.length === 0) {
		return null;
	}
	let maxForce = force_data[0];
	for (let i = 1; i < force_data.length; i++) {
		if (force_data[i] > maxForce) {
			maxForce = force_data[i];
		}
	}
	return maxForce;
}

function force_development_rate(peak_force, time_to_peak) {
	if (time_to_peak === 0) {
		return 0;
	} else {
		return peak_force / time_to_peak;
	}
}
// 4. 冲量，静冲量
function impulse(force_data, time_list) {
	let impulse = 0;
	if (time_list.length > 1) {
		for (let i = 0; i < time_list.length - 1; i++) {
			impulse += (force_data[i] + force_data[i + 1]) * 0.2 * 0.5;
		}
	} else {
		impulse = force_data[0] * 0.2;
	}
	return impulse;
}
// 5. 静冲量
function net_impulse(force_data, time_list, mass, g) {
	let impulse = 0;
	if (time_list.length > 1) {
		for (let i = 0; i < time_list.length - 1; i++) {
			impulse += (force_data[i] + force_data[i + 1]) * 0.2 * 0.5;
		}
		impulse = impulse - mass * g * time_list.length * 0.2;
	} else {
		impulse = force_data[0] * 0.2;
		impulse = impulse - mass * g * time_list.length * 0.2;
	}
	return impulse;
}

function displacement(v_up, time_list) {
	let displacement = 0;
	if (time_list.length > 1) {
		for (let i = 0; i < time_list.length - 1; i++) {
			displacement += (v_up[i] + v_up[i + 1]) * 0.02 * 0.5;
		}
	} else {
		displacement = v_up[0] * 0.02;
	}
	return displacement;
}
// 离心位移
function eccentric_displacement(v_down) {
	let displacement = 0;
	if (v_down.length > 1) {
		for (let i = 0; i < v_down.length - 1; i++) {
			displacement += (v_down[i] + v_down[i + 1]) * 0.02 * 0.5;
		}
	} else {
		displacement = v_down[0] * 0.02;
	}
	return displacement;
}
// 离心时间
function eccentric_time(v_down) {
	return 0.2 * v_down.length;
}
// 离心速度——离心平均速度
function eccentric_velocity(v_down) {
	if (v_down.length === 0) {
		return 0;
	}
	let sum = 0;
	for (let i = 0; i < v_down.length; i++) {
		sum += v_down[i];
	}
	return sum / v_down.length;
}
// 离心峰值速度
function eccentric_velocity_peak(v_down) {
	if (v_down.length === 0) {
		return null;
	}
	return Math.max(...v_down);
}
// 推进速度
function Propulsion_speed(acceleration_up, v_up) {
	let speed = [];
	for (let i = 0; i < acceleration_up.length; i++) {
		if (acceleration_up[i] > 0) {
			speed.push(v_up[i]);
		}
	}
	if (speed.length === 0) {
		return 0;
	}
	let sum = 0;
	for (let j = 0; j < speed.length; j++) {
		sum += speed[j];
	}
	return sum / speed.length;
}
// 做功量
function work_done_value(power_data) {
	let work = 0;
	if (power_data.length > 1) {
		for (let i = 0; i < power_data.length - 1; i++) {
			work += ((power_data[i] + power_data[i + 1]) * 0.2) / 2;
		}
	} else {
		if (power_data.length > 0) {
			work += power_data[0] * 0.2;
		}
	}
	return work;
}
// 做功总量
function total_work_value(work_done_value, total_work_value) {
	total_work_value.push(work_done_value);
	let sum = 0;
	for (let i = 0; i < total_work_value.length; i++) {
		sum += total_work_value[i];
	}
	return sum;
}
// 急速时间
function time_top(v_up) {
	if (v_up.length === 0) {
		return 0;
	}
	let maxIndex = 0;
	for (let i = 1; i < v_up.length; i++) {
		if (v_up[i] > v_up[maxIndex]) {
			maxIndex = i;
		}
	}
	return maxIndex * 0.2;
}
// 向心时间
function Centripetal_time(v_up) {
	return 0.2 * v_up.length;
}

// 功率
function power_loss(power_data, total_power_data) {
	if (power_data.length === 0) {
		return null;
	}
	let sum = 0;
	for (let i = 0; i < power_data.length; i++) {
		sum += power_data[i];
	}
	let average_power = sum / power_data.length;
	total_power_data.push(average_power);

	let max_power = -Infinity;
	for (let j = 0; j < total_power_data.length; j++) {
		if (total_power_data[j] > max_power) {
			max_power = total_power_data[j];
		}
	}

	let power_loss_value = (max_power - average_power) / max_power;
	return power_loss_value;
}
// 速度%
function v_up_loss(v_up, total_v_up_data) {
	if (v_up.length === 0) {
		return null;
	}
	let sum = 0;
	for (let i = 0; i < v_up.length; i++) {
		sum += v_up[i];
	}
	let average_power = sum / v_up.length;
	total_v_up_data.push(average_power);

	let max_v_up = Math.max(...total_v_up_data);
	let v_loss_value = (max_v_up - average_power) / max_v_up;
	return v_loss_value;
}
// 功率峰值
function power_peak_loss(power_data, total_power_peak_data) {
	if (power_data.length === 0) {
		return null;
	}
	let average_power = Math.max(...power_data);
	total_power_peak_data.push(average_power);

	let max_v_up = Math.max(...total_power_peak_data);
	let v_loss_value = (max_v_up - average_power) / max_v_up;
	return v_loss_value;
}
// 速度峰值
function v_peak_loss(v_up, total_v_peak_data) {
	if (v_up.length === 0) {
		return null;
	}
	let average_power = v_up;
	total_v_peak_data.push(average_power);
	let max_v_up = Math.max(...total_v_peak_data);
	let v_loss_value = (max_v_up - average_power) / max_v_up;
	return v_loss_value;
}
// 相对功率 每公斤体重输出功率的能力
function relative_power(total_power_data, mass) {
	if (total_power_data.length === 0) {
		return null;
	}
	return total_power_data[total_power_data.length - 1] / mass;
}
// 相对功率峰值
function relative_power_peak(power_data, mass) {
	if (power_data.length === 0) {
		return null;
	}
	return Math.max(...power_data) / mass;
}
// 功率发展率
function Power_development_rate(power_data) {
	if (power_data.length === 0) {
		return null;
	}
	let maxIndex = 0;
	for (let i = 1; i < power_data.length; i++) {
		if (power_data[i] > power_data[maxIndex]) {
			maxIndex = i;
		}
	}
	let top_time = maxIndex * 0.2;
	return Math.max(...power_data) / top_time;
}
// 0.2s力
function force_0_2(force_data) {
	if (force_data.length === 0) {
		return null;
	}
	return force_data[0];
}
// 0.2s速度
function v_0_2(v_up) {
	if (v_up.length === 0) {
		return null;
	}
	return v_up[0];
}
// 0.2s功率
function power_0_2(power_data) {
	if (power_data.length === 0) {
		return null;
	}
	return power_data[0];
}
// 0.2s冲量
function impulse_0_2(force_data) {
	if (force_data.length === 0) {
		return null;
	}
	return force_data[0] * 0.2;
}
// 本次消耗卡路里
function calories_burned(work) {
	return (work * 0.239) / 1000;
}
// 消耗的总卡路里
function total_calories(calories_burned, total_calories) {
	total_calories.push(calories_burned);
	let sum = 0;
	for (let i = 0; i < total_calories.length; i++) {
		sum += total_calories[i];
	}
	return sum;
}
// opl
function opl(mass) {
	return mass;
}

function check_zero_two_five(data, l, r, val) {
	let cnt = 0;
	l = Math.max(0, l);
	for (let i = l; i <= r; i++) {
		if (data[i] <= val) {
			cnt++;
			if (cnt == 3) {
				return 1;
			}
		}
	}
	return 0;
}

function is_limit(v_up, order, n) {
	if (order.length === 0) {
		return [v_up, order];

	} else if ((order[0][order[0].length - 1] - order[0][0]) > n) {
		v_up = [v_up[0].slice(0, n)];
		order = [
			[order[0][0], parseInt(order[0][0]) + n]
		];
		return [v_up, order];

	} else {
		return [v_up, order];
	}
}
// 获取负荷建议范围
const get_suggest = function (aim, action, lrm) {
	var suggest = []
	if (aim == 0) {
		if (action == 0) {
			suggest = [0.6 * lrm, 0.8 * lrm];
		} else if (action == 1 || action == 2) {
			suggest = [0.6 * lrm, 0.8 * lrm]
		}
	} else if (aim == 1) {
		if (action == 0) {
			suggest = [0.8 * lrm, 1 * lrm]
		} else if (action == 1 || action == 2) {
			suggest = [0.8 * lrm, 1 * lrm]
		}
	} else if (aim == 2) {
		if (action == 0) {
			suggest = [0.4 * lrm, 0.6 * lrm]
		} else if (action == 1 || action == 2) {
			suggest = [0.4 * lrm, 0.6 * lrm]
		}
	}
	return suggest;
}



// write_txt(bef_velocities, displace, acceleration_data, flag_v)
function write_txt(vec_data, disp_data, acc_data, avg_v, flag) {
	//速度 位移，加速度，标志位
	const fs = uni.getFileSystemManager()
	const filePath = `${uni.env.USER_DATA_PATH}/result.docx`
	let flag_msg = "NO";
	if (flag == true) {
		flag_msg = "YES"
	}
	const vec_txt = JSON.stringify(vec_data);
	const acc_txt = JSON.stringify(acc_data);
	const disp_txt = JSON.stringify(disp_data);
	const avg_v_txt = JSON.stringify(avg_v);
	// 追加写入文件
	fs.appendFile({
		filePath: filePath,
		// data: flag_msg + '\nvec' + vec_txt + '\nacc' +  acc_txt + '\ndisplacement' + disp_txt +  '\n' ,
		data: flag_msg + '\nvec' + vec_txt + '\ndisplacement' + disp_txt + '\n',
		encoding: 'utf8',
		success: () => {
			// console.log("写入文件成功！");
		},
		fail: (err) => {
			console.error('写入文件失败', err);
		},
	});
}


// 简易版请求函数
const simple_update = function (x, y, z, alpha, beta, gamma, aim, action, lrm, m_data, n_base, gg, tim) {
	lrm = lrm || 100
	m_data = m_data || 70
	// console.log('x',x);
	// console.log('y',y);
	// console.log('z',z);
	// console.log('alpha',alpha);
	// console.log('beta',beta);
	// console.log('gamma',gamma);
	// console.log('aim',aim);
	// console.log('action',action);
	// console.log('lrm',lrm);
	// console.log('m_data',m_data);
	// console.log('n_base',n_base);
	// console.log('gg',gg);
	// console.log('tim',tim);
	
	let data = VueEvent.xyz_to_y(x, y, z, alpha, beta, gamma);

	var begin_data = {
		aim: aim,
		action: action,
		lrm: lrm,
		m_data: m_data,
		gg: gg,
		data: data
	}
	console.log("???发送请求的数据",begin_data);
	let g = 9.8
	let local_g = 0;
	let loss = 0;
	let flag_n = 0;
	let dataall = [];
	let s = 1;
	let flag_break = 0;
	let flag = false;
	let return_local_g = 0;
	if (gg == 0) {
		local_g = data.length >= 130 ? data.slice(30, 130).reduce((sum, val) => sum + val, 0) / (130 - 30) : data[
			data.length - 1];
	} else {
		local_g = gg;
	}
	if (gg == 0 && data.length >= 130) {
		console.log("换新local_g")
		return_local_g = local_g;
	}
	data = data.slice(30, data.length);
	// 确保 local_g 是数字类型
	local_g = parseFloat(local_g);
	// 若 local_g 是 NaN，给出默认值
	if (isNaN(local_g)) {
		local_g = 0;
	}
	local_g = local_g.toFixed(7);
	let time = tim; // 时间
	let total_data = [];
	let add_txt_data = [];
	for (let i of data) {
		let temp_list = [];
		// temp_list.push(-1 * ((parseFloat(i) - local_g) * 10));
		let temp_single = parseFloat((parseFloat(i) - parseFloat(local_g)).toFixed(7));
		temp_list.push(temp_single);
		add_txt_data.push(temp_single);
		// console.log("add",-1 * ((parseFloat(i) - local_g) * 10));
		// filter1(temp_list, 0.0001, 0.001, 18);
		// console.log("temp_list111",temp_list);
		total_data.push(temp_list[0]);
	}
	// 完整的滤波处理后的加速度数据total_data
	// let acceleration_data = total_data; //纯加速度数据
	// console.log("add_txt_data",add_txt_data)
	add_txt_data = add_txt_data.map(num => {
		// 确保是数字类型
		num = parseFloat(num);
		// 使用 toFixed(7) 保留七位小数，再转换回数字类型
		return parseFloat(num.toFixed(7));
	});
	let acceleration_data = add_txt_data; // 纯加速度数据
	// abs（加速度i - 加速度i-1）/0.02>300
	// 加速度i=0
	let noise_arg = noise_options[action]
	for (let i = 1; i < acceleration_data.length; i++) {
		if (Math.abs(acceleration_data[i] - acceleration_data[i - 1]) / 0.02 > noise_arg) {
			acceleration_data[i] = 0;
		}
	}
	// console.log("修正后",acceleration_data);
	// console.log("???local_g\n",local_g);
	// console.log("???acceleration_data\n", acceleration_data);

	// return false;
	// acceleration_data = acccccc

	let jifen_v_l_options = [-0.08, -0.12, -0.15, -0.08, -0.10, -0.13, -0.02, -0.13, -0.15, -0.15]
	let jifen_v_r_options = [0.10, 0.11, 0.12, 0.05, 0.12, 0.08, 0.12, 0.08, 0.12, 0.12]
	let jifen_v_arg_options = [0.90, 0.80, 0.85, 0.80, 0.85, 0.80, 0.85, 0.80, 0.85, 0.85]


	let jifen_disp_l_options = [-0.03, -0.015, -0.12, 0, -0.12, -0.10, -0.05, -0.10, -0.10, -0.12]
	let jifen_disp_r_options = [0.12, 0.12, 0.12, 0.10, 0.12, 0.04, 0, 0.04, 0.12, 0.12]
	let jifen_disp_arg_options = [0.95, 0.93, 0.90, 0.93, 0.90, 0.95, 1.00, 0.95, 0.85, 0.90]


	let velocities = accumulate_acceleration_to_velocity_4(acceleration_data,
		time,
		jifen_v_l_options[action],
		jifen_v_r_options[action],
		jifen_v_arg_options[action]) // 速度数据

	//位移
	let displace = accumulate_acceleration_to_velocity_4(velocities,
		time,
		jifen_disp_l_options[action],
		jifen_disp_r_options[action],
		jifen_disp_arg_options[action])

	let displace_flag = false;
	let displace_index = 0;
	let flag_v = false;
	let bef_velocities = velocities;
	// console.log("displace_order")
	// console.log("displace",displace)
	// console.log("velocities",velocities)
	// return false ; 
	let temp_res = []
	try {
		temp_res = displace_order_new(displace, velocities, action) || [
			[], false, 0, false
		];
	} catch (e) {
		console.warn("displace_order_new error:", e);
		temp_res = [
			[], false, 0, false
		];
	}


	if (!Array.isArray(temp_res) || temp_res.length < 4) {
		console.error("displace_order 返回值结构异常:", temp_res);
	} else {
		[velocities, displace_flag, displace_index, flag_v] = temp_res;
	}
	// console.log("???velocities",velocities);
	// console.log("???displace",displace);
	// console.log("???displace_flag",displace_flag);
	// console.log("???displace_index",displace_index);
	// console.log("???flag_v",flag_v);
	let speedThreshold = 0.05;

	// return false ;
	// console.log("velocities",velocities)
	// console.log("acceleration_data",acceleration_data)
	// console.log("bef_velocities",bef_velocities)
	let [v_up, v_down, acceleration_up, order] = new_cut_list(velocities, acceleration_data, bef_velocities,
		action);

	// write_txt(bef_velocities, displace, acceleration_data, flag_v)
	// console.log("v_up",v_up)
	// console.log("v_down",v_down)
	// console.log("acceleration_up",acceleration_up)
	// console.log("order",order)


	// let [v_up, v_down, acceleration_up, acceleration_down, order] = cut_list(velocities, bef_velocities);
	// console.log("order",order)

	// [v_up, order]=is_limit(v_up,order,600);

	// console.log("v_up",v_up);
	// console.log("v_down",v_down);
	// console.log("acceleration_up",acceleration_up);
	// console.log("acceleration_down",acceleration_down);
	// console.log("???order", order);
	let index = 0;
	let n = 0;

	// 指标计算
	// console.log("force_data!!!")
	// console.log("acceleration_up",acceleration_up)
	// console.log("m_data",m_data)
	// console.log("local_g",local_g)
	let force_data = calculate_force(acceleration_up, m_data, local_g);
	// 1 平均速度
	let averagy_v_value = averagy_v(v_up);
	let power_data = caculate_power(v_up, force_data);
	// 2 平均功率
	let averagy_power_value = averagy_power(power_data);
	// 3 速度峰值
	let v_peak = Math.max(...v_up);
	// 4 功率峰值
	let power_peak = Math.max(...power_data);
	write_txt(bef_velocities, displace, acceleration_data, Math.abs(averagy_v_value), flag_v)
	// console.log("force_data",force_data)
	// console.log("averagy_v_value",averagy_v_value)
	// console.log("power_data",power_data)
	// console.log("averagy_power_value",averagy_power_value)
	// console.log("v_peak",v_peak)
	// console.log("power_peak",power_peak)

	// console.log("本次请求结果是",flag_v)
	if ( Math.abs(averagy_v_value)  <=0.12 ){
		flag_v = false ;
	}
	let res = {
		flag: flag_v,
		del_index: order[1][1],
		local_g: return_local_g,
		// 指标
		averagy_v_value: Math.abs(averagy_v_value),
		averagy_power_value: Math.abs(averagy_power_value),
		v_peak: Math.abs(v_peak),
		power_peak: Math.abs(power_peak),
	}
	return res;
}












const complex_new = function (aim, action, lrm, m_data, n_base, gg) {
	// 加速度 aim action 1rm m_data accelarate_Data n_base gg
	// console.log("???进入请求函数了");

	var time1 = new Date();
	let data = VueEvent.xyz_to_y(VueEvent.sharedData.measured_acceleration_x,
		VueEvent.sharedData.measured_acceleration_y,
		VueEvent.sharedData.measured_acceleration_z,
		VueEvent.sharedData.alpha,
		VueEvent.sharedData.beta,
		VueEvent.sharedData.gamma);


	var begin_data = {
		aim: aim,
		action: action,
		lrm: lrm,
		m_data: m_data,
		gg: gg,
		data: data
	}
	console.log("???发送请求的数据", begin_data);
	let g = 9.8
	let local_g = 0;
	let loss = 0;
	let flag_n = 0;
	let dataall = [];
	let total_work_value2 = [];
	let total_power_data = [];
	let total_v_up_data = [];
	let total_power_peak_data = [];
	let total_v_peak_data = [];
	let total_calories_list = [];
	let s = 1;

	if (n_base == 0) {
		local_g = data.length >= 130 ? data.slice(30, 130).reduce((sum, val) => sum + val, 0) / (130 - 30) :
			data[
				data.length - 1];
	} else if (n_base >= 1) {
		local_g = gg;
	}
	data = data.slice(30, data.length);

	// 确保 local_g 是数字类型
	local_g = parseFloat(local_g);
	// 若 local_g 是 NaN，给出默认值
	if (isNaN(local_g)) {
		local_g = 0;
	}
	local_g = local_g.toFixed(7);
	let time = 0.02; // 时间
	let total_data = [];
	let add_txt_data = [];
	// console.log("local_g",local_g);
	// console.log("修正前",data);
	for (let i of data) {
		let temp_list = [];
		// temp_list.push(-1 * ((parseFloat(i) - local_g) * 10));
		let temp_single = parseFloat((parseFloat(i) - parseFloat(local_g)).toFixed(7));
		temp_list.push(temp_single);
		add_txt_data.push(temp_single);
		// console.log("add",-1 * ((parseFloat(i) - local_g) * 10));
		// filter1(temp_list, 0.0001, 0.001, 18);
		// console.log("temp_list111",temp_list);
		total_data.push(temp_list[0]);
	}
	// 完整的滤波处理后的加速度数据total_data
	// let acceleration_data = total_data; //纯加速度数据
	add_txt_data = add_txt_data.map(num => {
		// 确保是数字类型
		num = parseFloat(num);
		// 使用 toFixed(7) 保留七位小数，再转换回数字类型
		return parseFloat(num.toFixed(7));
	});
	let acceleration_data = add_txt_data; // 纯加速度数据
	// console.log("修正后",acceleration_data);
	// console.log("???local_g\n",local_g);
	// console.log("???acceleration_data\n", acceleration_data);
	let velocities = accumulate_acceleration_to_velocity_4(acceleration_data, time); // 速度数据

	let displace = accumulate_acceleration_to_velocity_4(velocities, time)
	let [displace_flag, displace_index] = displace_order(displace, velocities)
	// console.log("???velocities",velocities);
	// console.log("???displace",displace);
	// console.log("???displace_flag",displace_flag);
	// console.log("???displace_index",displace_index);
	let speedThreshold = 0.12;



	let [v_up, v_down, acceleration_up, acceleration_down, order] = cut_list(velocities, speedThreshold,
		acceleration_data);
	[v_up, order] = is_limit(v_up, order, 600);
	// console.log("v_up",v_up);
	// console.log("v_down",v_down);
	// console.log("acceleration_up",acceleration_up);
	// console.log("acceleration_down",acceleration_down);
	// console.log("???order", order);
	let flag = 0;
	let index = 0;
	let n = 0;
	if (v_up.length >= 1) {
		[flag, index] = is_connect_n0(acceleration_data, displace_index, 1, 10);
		// console.log("???索引是",index);
		index = index > order[0][0] ? index : order[0][0];

		if (index < order[0][1]) {
			[flag, index] = is_connect_n0(acceleration_data, order[0][1], 1, 10);
		}

		let flag_check = check_zero_two_five(acceleration_data, index - 80, index, -0.015);
		// console.log("???前置数据",acceleration_data.slice(index-80,index));
		// if (v_up[0].length==100){
		if (acceleration_data.length == 600) {
			flag_check = 1;
		} else {
			flag_check = check_zero_two_five(acceleration_data, index - 80, index, -0.015);
		}
		console.log("flag_check", flag_check);
		flag = displace_flag * flag;
		flag = flag * flag_check;
		console.log("flag", flag);
		// flag = 1;
		// index = index if index > order[0][-1] else order[0][-1]

	} else {
		flag = 0;
		index = 0;
	}
	// console.log("flag",flag);
	// console.log("???index", index);
	// console.log("???v_up",v_up);
	// console.log("???flag_n",flag_n);
	if (v_up.length > flag_n) {
		flag_n = v_up.length;
		// console.log(`${v_up.length}`);???

		// 计算速度损失和每次运动的平均速度（使用上升段）
		let [loss_data, average_speeds] = velocity_loss_try(v_up);
		// console.log("loss_data",loss_data);
		// console.log("average_speeds",average_speeds);
		while (n < average_speeds.length) {
			// console.log(`\n第${s + 1}组，第${n + 1}次`);

			let v = n < average_speeds.length ? average_speeds[n] : 0;
			// console.log(`当前动作的平均速度: ${v}`);

			if (n < loss_data.length) {
				loss = loss_data[n];
				// console.log(`当前动作的速度损失: ${loss}`);
				let v_up1 = v_up[n];
				let v_down1 = n < v_down.length ? v_down[n] : v_up1;
				let acceleration_up1 = acceleration_up[n];
				if (!dataall[n]) {
					dataall[n] = {}; // 如果是 undefined，就初始化一个空对象
				}

				// console.log("v_up1",v_up1);
				// console.log("v_down1",v_down1);
				// console.log("acceleration_up1",acceleration_up1);

				let time_list = generateTimeList(acceleration_up1);
				let force_data = calculate_force(acceleration_up1, m_data, g)
				let time_to_peak_force = getTimeToPeakForce(time_list, force_data);
				let force_peak = peak_force(force_data)
				let force_development_rate1 = force_development_rate(force_peak, time_to_peak_force)
				let impulse_value = impulse(force_data, time_list)
				let net_impulse_value = net_impulse(force_data, time_list, m_data, g)

				let displacement_value = displacement(v_up1, time_list)
				let eccentric_displacement_value = eccentric_displacement(v_down1)
				let eccentric_time1 = eccentric_time(v_down1)
				let eccentric_velocity1 = eccentric_velocity(v_down1)
				let eccentric_velocity_peak1 = eccentric_velocity_peak(v_down1)

				// 有了已经
				let averagy_v_value = averagy_v(v_up1)
				let power_data = caculate_power(v_up1, force_data)
				let averagy_power_value = averagy_power(power_data)
				let averagy_force_value = averagy_force(force_data)
				let Propulsion_speed_value = Propulsion_speed(acceleration_up1, v_up1)
				let work_done_value1 = work_done_value(power_data)
				let total_work_value1 = total_work_value(work_done_value1,
					total_work_value2)
				let time_top1 = time_top(v_up1)
				let Centripetal_time1 = Centripetal_time(v_up1)
				// console.log("before v_up",v_up1);
				let tpp = v_up1;
				v_up1 = peak_force(v_up1)
				let power_loss1 = power_loss(power_data, total_power_data)
				let v_up_loss1 = v_up_loss(v_up1, total_v_up_data)
				let power_peak_loss1 = power_peak_loss(power_data,
					total_power_peak_data)
				let power_peak = Math.max(...power_data);
				let v_peak_loss1 = v_peak_loss(v_up1, total_v_peak_data)
				let relative_power1 = relative_power(total_power_data, m_data)
				let relative_power_peak1 = relative_power_peak(power_data, m_data)
				let Power_development_rate1 = Power_development_rate(power_data)
				let force_0_21 = force_0_2(force_data)
				// console.log("v_up1!!!!!!!!!!",v_up1);
				let v_0_21 = v_0_2(tpp);

				let power_0_21 = power_0_2(power_data)
				let impulse_0_21 = impulse_0_2(force_data)
				let calories_burned1 = calories_burned(work_done_value1)
				let total_calories1 = total_calories(calories_burned1,
					total_calories_list) //total_calories_list
				let opl1 = opl(m_data)

				// console.log("force_data",force_data);
				// console.log("averagy_v_value",averagy_v_value);
				// console.log("power_data",power_data);
				// console.log("averagy_power_value",averagy_power_value);
				// console.log("v_peak",v_peak);
				// console.log("power_peak",power_peak);
				if (!dataall[n]) {
					dataall[n] = {}; // 如果是 undefined，就初始化一个空对象
				}
				dataall[n]["avg_speed"] = averagy_v_value;
				dataall[n]["max_speed"] = v_up1;
				dataall[n]["avg_power"] = averagy_power_value;
				dataall[n]["max_power"] = power_peak;

				dataall[n]["averagy_force_value"] = averagy_force_value;
				dataall[n]["max_strive"] = force_peak;
				dataall[n]["strive_rate"] = force_development_rate1;
				dataall[n]["power_loss"] = power_loss1;

				dataall[n]["impulse"] = impulse_value;
				dataall[n]["net_impulse"] = net_impulse_value;
				dataall[n]["work"] = work_done_value1;
				dataall[n]["pre_work"] = total_work_value1;

				dataall[n]["power_max_loss"] = power_peak_loss1;
				dataall[n]["speed_max_loss"] = v_peak_loss1;
				dataall[n]["relative_power"] = relative_power1;
				dataall[n]["relative_max_power"] = relative_power_peak1;

				dataall[n]["centrifugal_speed"] = eccentric_velocity1;
				dataall[n]["centrifugal_max_speed"] = eccentric_velocity_peak1;
				dataall[n]["centrifugal_time"] = eccentric_time1;
				dataall[n]["rpd"] = Power_development_rate1;

				dataall[n]["zero_point_two_speed"] = v_0_21;
				dataall[n]["zero_point_two_power"] = power_0_21;
				dataall[n]["zero_point_two_strive"] = force_0_21;
				dataall[n]["zero_point_two_momentum"] = impulse_0_21;

				dataall[n]["calorie"] = calories_burned1;
				dataall[n]["total_calorie"] = total_calories1;
				dataall[n]["opl"] = Number(opl1);
				dataall[n]["toward_heart_time"] = Centripetal_time1;

			} else {
				loss = 0;
			}
			if (!dataall[n]) {
				dataall[n] = {}; // 如果是 undefined，就初始化一个空对象
			}
			// console.log("???average_speeds",average_speeds);
			// if (average_speeds.length > 0 && flag === 1) {
			if (flag === 1) {
				dataall[n]["updata_flag"] = 1;
				dataall[n]["delete_index"] = index;
				dataall[n]["第几个"] = n + 1 + n_base;
				dataall[n]["n_base"] = n + 1 + n_base;
			} else {
				dataall[n]["updata_flag"] = 0;
				dataall[n]["delete_index"] = index;
				dataall[n]["第几个"] = n + n_base;
				dataall[n]["n_base"] = n + n_base;
			}


			dataall[n]["local_g"] = local_g;
			dataall[n]["loss"] = loss;

			let message, request_load;
			if (aim === 0) {
				if (action === 0) {
					message = VBT_juge_group_plasticity_low(v, loss, n, s);
					request_load = [0.6 * lrm, 0.8 * lrm];
				} else {
					message = VBT_juge_group_plasticity_up(v, loss, n, s);
					request_load = [0.6 * lrm, 0.8 * lrm];
				}
			} else if (aim === 1) {
				if (action === 0) {
					message = VBT_juge_group_plasticity_low(v, loss, n, s);
					request_load = [0.8 * lrm, 1 * lrm];
				} else {
					message = VBT_juge_group_plasticity_up(v, loss, n, s);
					request_load = [0.8 * lrm, 1 * lrm];
				}
			} else if (aim === 2) {
				if (action === 0) {
					message = VBT_juge_group_plasticity_low(v, loss, n, s);
					request_load = [0.4 * lrm, 0.6 * lrm];
				} else {
					message = VBT_juge_group_plasticity_up(v, loss, n, s);
					request_load = [0.4 * lrm, 0.6 * lrm];
				}
			}

			// 处理消息映射
			const messageMap = {
				"目前没你鸟事,继续练你的": "请继续训练",
				"菜就加杠铃重量": "建议增加重量",
				"菜就减杠铃重量": "建议减少重量",
				"滚回去重开": "动作不规范，请重新开始"
			};
			message = messageMap[message] || message;

			dataall[n]["message"] = message;
			request_load = request_load.map(i => Math.round(i * 100) / 100);
			dataall[n]["message1"] = `建议负重${request_load[0]}kg-${request_load[1]}kg`;
			// console.log(message);

			// 根据不同的 VBT 规则进行适配
			if (["建议增加重量", "建议减少重量", "动作不规范，请重新开始"].includes(message)) {
				n++;
			}

			if (message === "请继续训练") {
				n++;
				if (n > 8 && n < 12 && loss >= 0.3) {
					message = `目前最佳训练数量为每组${n}个`;
					dataall[n]["message"] = message;
					n = 0;
					flag_break = 1;
					break;
				}
				continue;
			}

			if (message.startsWith("你最好")) {
				message = `目前最佳训练数量为每组${n}个`;
				dataall[n]["message"] = message;
				n = 0;
				flag_break = 1;
				break;
			}
		}
	}
	// console.log("请求后的修正后的加速度2！！！\n", data);
	var result = {
		msg: dataall.length !== 0 ? dataall : [{
			"averagy_power_value": 0,
			"averagy_v_value": 0,
			"delete_index": 0,
			"local_g": 0,
			"loss": 0,
			"message": "暂未检测到完成一个完整的动作",
			"message1": "暂未检测到完成一个完整的动作",
			"n_base": 0,
			"power_peak": 0,
			"updata_flag": 0,
			"v_peak": 0,
			"第几个": 0,
			// "第几组": 0
		}],
		v: add_txt_data
	}
	// console.log("???结果试试",result);
	var time2 = new Date();
	// console.log("???time",time2-time1);
	return result;
}

export default {
	get_suggest,
	simple_update,
	complex_new,
	displace_order_new
}